package org.shan.hangtian;

import org.shan.hangtian.properties.HangtianProperties;
import org.shan.hangtian.server.HangTIanDeviceServer;
import org.shan.hangtian.server.handler.DataDecode;
import org.shan.hangtian.server.handler.DataEncode;
import org.shan.hangtian.server.handler.DataSaveHandle;
import org.shan.hangtian.server.handler.EventHandle;
import org.shan.hangtian.server.session.SessionManager;
import org.shan.hangtian.tp.HangtianPacket;
import org.shan.hangtian.tp.RunMode;

import java.util.Timer;
import java.util.TimerTask;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by amanda.shan on 2020/10/2.
 */
public class DeviceServer implements DeviceControl {

    private HangTIanDeviceServer deviceNettyServer;

    @Override
    public void start() throws Exception {
        HangtianProperties properties = HangtianProperties.getInstance();

        deviceNettyServer = new HangTIanDeviceServer(new NioEventLoopGroup(), new NioEventLoopGroup(),
                "hangtian");

        deviceNettyServer.start(new ChannelInitializer() {
            @Override
            protected void initChannel(Channel ch) throws Exception {

                ch.pipeline().addLast("idleStateHandler",
                        new IdleStateHandler(properties.getTimeOut(), 0, 0));

                ch.pipeline().addLast(new EventHandle());
                ch.pipeline().addLast(new DataSaveHandle());
                ch.pipeline().addLast(new DataDecode());
                ch.pipeline().addLast(new DataEncode());
            }
        }, properties.getPort());
    }

    @Override
    public void stop() {
        if (deviceNettyServer != null) {
            deviceNettyServer.shutdown();
        }
    }


    @Override
    public boolean isRun() {
        return deviceNettyServer != null && deviceNettyServer.isRun();
    }

    public static void main(String[] args) throws Exception {

        SessionManager.getInstance().setSessionLis(new SessionManager.SessionLis() {
            @Override
            public void online() {
                System.out.println("在线");
            }

            @Override
            public void offline() {
                System.out.println("离线");
            }
        });

        new DeviceServer().start();

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                Channel onlineChannel = SessionManager.getInstance().getOnlineChannel();

                if (onlineChannel != null){
                    onlineChannel.writeAndFlush(HangtianPacket.changeMusic(RunMode.MODE_1, (byte) 1));
                }
            }
        }, 0, 1000);

    }

}
